<?php
namespace app\admin\services;

use app\admin\exception\AdminException;
use app\admin\model\Auth\AdminModel;
use app\admin\services\system\SystemMenusServices;
use support\bootstrap\Cache;

class AdminServices extends BaseServices
{

    /**
     * 验证登录
     * @param string $username
     * @param string $password
     * @return array|\think\Model
     * @throws AdminException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function verifyLogin(string $username, string $password)
    {
        $adminModel = new AdminModel();
        $adminInfo = $adminModel->get(['account' => $username]);
        if (!$adminInfo) {
            throw new AdminException('管理员不存在!');
        }
        if (!$adminInfo->status) {
            throw new AdminException('您已被禁止登录!');
        }
        if (!password_verify($password, $adminInfo->pwd)) {
            throw new AdminException('账号或密码错误，请重新输入');
        }
        $adminInfo->last_time = time();
        $adminInfo->last_ip = request()->getRemotePort();
        $adminInfo->login_count++;
        $adminInfo->save();
        return $adminInfo;
    }

    /**
     * 登录
     * @param string $username
     * @param string $password
     * @param string $type
     * @return array
     * @throws AdminException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login( string $username, string $password )
    {
        $adminInfo = $this->verifyLogin($username, $password);
        $expireTime = 3600 * 24 * 10;
        $endTime = time() + $expireTime;
        $id = $adminInfo->id;
        $token = $this->createToken([
            'id' => $id,
            'expire' => $expireTime,
        ] , $expireTime , '' , 'webman' , 'login' , $id );
        //将token存储于令牌桶中
        $cacheData = [
            'uid' => $id,
            'token' => $token,
            'exp' => $endTime
        ];
        $cacheRes = Cache::set(md5($token) , $cacheData , $expireTime);
        if(!$cacheRes){
            throw new AdminException("存储令牌失败");
        }


        /** @var SystemMenusServices $services */
        $services = new SystemMenusServices();
        [$menus, $uniqueAuth] = $services->getMenusList($adminInfo->roles, (int)$adminInfo['level']);
        return [
            'token' => $token,
            'expires_time' => $endTime,
            'menus' => $menus,
            'unique_auth' => $uniqueAuth,
            'user_info' => [
                'id' => $adminInfo->getData('id'),
                'account' => $adminInfo->getData('account'),
                'head_pic' => $adminInfo->getData('head_pic'),
            ],
            'logo' => '',
            'logo_square' => '',
            'version' => 'v1.0.0',
            'newOrderAudioLink' => ''
        ];
    }
}